package com.sq.goodline.service;

import java.io.File;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sq.goodline.config.JobConfig;
import com.sq.goodline.config.OssConfig;
import com.sq.goodline.dao.AudioDetailDao;
import com.sq.goodline.dao.po.AudioDetail;
import com.sq.goodline.util.DateUtils;
import com.sq.goodline.util.FileUtils;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class RecService {
	@Resource
	OssConfig ossConfig;
	@Resource
    JobConfig jobConfig;
	@Autowired
	AudioDetailDao audioDetailDao;
	@Autowired
	OssService ossService;
	
	/**
	 * 将vos生成的.rec录音文件与话单关联
	 * @throws Exception 
	 */
	public StringBuffer recRelaCallDetail() throws Exception {
		StringBuffer mailContext = new StringBuffer();
		QueryWrapper<AudioDetail> qw = new QueryWrapper<>();
		qw.eq("audio_status", -1);//-1 初始数据
		qw.orderByAsc("create_time");//升序排列
		qw.last("LIMIT 50");//最多查*笔
		List<AudioDetail> audioDetailList = audioDetailDao.selectList(qw);
		if(audioDetailList==null) {
			log.debug("无待转换录音");
			return null;
		}
		for(AudioDetail detail:audioDetailList) {
			//本地硬盘上找到对应的rec录音文件
			File recFile = findRec(detail);
			if(recFile==null) {
				mailContext.append("\r\n未找到rec录音文件,flowno:"+detail.getFlowno());
			}else {
				String mySign = DigestUtils.md5Hex(detail.getFlowno()+ossConfig.getSignSalt());
				String recordFileUrl = "/api/download?flowno="+detail.getFlowno()+"&sign="+mySign;
				detail.setRecordFileUrl(recordFileUrl);
				detail.setOriginRecName(recFile.getName());
				detail.setRecRecordPath(recFile.getAbsolutePath());
				detail.setAudioStatus(0);//录音状态 -1 初始数据, 0 已关联话单, 1 已上传OSS
				detail.setPushResult(0);//数据推送结果：-1 初始数据,0待推送、1成功，2失败
				int i = audioDetailDao.updateById(detail);
				log.info("更新录音状态完成：{}",i);
			}
		}
		return mailContext;
	}
	
	/**
	 * 本地硬盘上找到对应的rec录音文件
	 * @param detail
	 * @return 
	 * @throws Exception
	 */
	private File findRec(AudioDetail detail) throws Exception {
		Date d = new Date();
		d.setTime(detail.getStarttime());//通话起始时间的小时，通常是该笔录音的存放子目录
		
		//rec原始录音保存在：/kunshi1-data/record/yyyyMMdd/HH
		String folderPath = jobConfig.getRecLocalPath()+"/"+DateUtils.formatDate(d,"yyyyMMdd/HH");
		File file = FileUtils.findFileByEnds(folderPath, detail.getFlowno()+".rec");
		
        //如果未找到录音文件，则跨到下1小时再找一遍
        if(file==null) {
        	log.info("未找到对应的.rec录音文件:{},flowno:{}",folderPath,detail.getFlowno());
        	Date d2 = DateUtils.addHours(d, 1);
        	folderPath = jobConfig.getRecLocalPath()+"/"+DateUtils.formatDate(d2,"yyyyMMdd/HH");
        	file = FileUtils.findFileByEnds(folderPath, detail.getFlowno()+".rec");
        }
        
        if(file==null) {
        	log.info("未找到对应的.rec录音文件,flowno:{}",folderPath,detail.getFlowno());
        	return null;
        }else {
        	log.info("找到录音文件：{}",file.getAbsolutePath());
        	return file;
        }
	}
	
	/**
	 * 定期将本地rec文件上传oss
	 * rec存于oss路径规范：yyyy/MM/dd/flowno_时间戳.rec
	 */
	public StringBuffer recUploadOss() {
		StringBuffer mailContext = new StringBuffer();
		Date d = new Date();
		Date d2 = DateUtils.addDays(d, -jobConfig.getRecSaveLocalDay());
		QueryWrapper<AudioDetail> qw = new QueryWrapper<>();
		qw.eq("audio_status", 0);//录音状态 -1 初始数据, 0 本地录音文件已关联话单, 1 已上传OSS
		qw.lt("create_time", d2);//查N天前的
		qw.last("LIMIT 200");//最多查*笔
		List<AudioDetail> audioDetailList = audioDetailDao.selectList(qw);
		if(audioDetailList==null) {
			log.debug("无待上传录音");
			return null;
		}
		
		for(AudioDetail detail:audioDetailList) {
			File recFile = new File(detail.getRecRecordPath());
			String objectName = DateUtils.getDayString(detail.getStarttime(), "yyyy/MM/dd/")+detail.getFlowno()+"_"+System.currentTimeMillis()+".rec";
			boolean upFlag = ossService.fileUploadOss(recFile, objectName);
			if(upFlag) {
				log.info("上传成功：{}",objectName);
				detail.setAudioStatus(1);//1 已上传OSS
				detail.setRecOssPath(objectName);
				int a = audioDetailDao.updateById(detail);
				log.info("更新AudioDetail完成：{}",a);
			}else {
				mailContext.append("\r\n上传OSS失败："+detail.getRecRecordPath());
			}
		}
		return mailContext;
	}
}
